import requests
from hashlib import md5

class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

'''
12306模拟登录编码流程
1、 使用selenium打开登录页面
2、 对当前selenium打开的这张页面进行截图
3、 对当前图片局部区域（验证码图片）进行载减
    好处：将验证码图片和模拟登录进行--对应
4、 使用超级鹰识别验证码图片（坐标）
'''
import time
from selenium import webdriver
from PIL import Image
from selenium.webdriver import ActionChains

bro = webdriver.Chrome(executable_path='./chromedriver')
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
time.sleep(1)

# 设置浏览器窗口最大化
bro.maximize_window()  # 设置打开页面最大化,目的是更好的截取错误图

login_index = bro.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a')
login_index.click()
time.sleep(2)

# save_screenshot就是将当前页面进行截图且保存
bro.get_screenshot_as_file('aa.png')


# 确认验证码图片对应的左上角和右下角的坐标（裁剪的区域就确定）
code_img_ele = bro.find_element_by_xpath('//img[@id="J-loginImg"]')
location = code_img_ele.location # 返回验证码左上角坐标
size = code_img_ele.size # 验证码标签对应的长和宽
# 截图由于本系统显示缩放与布局为125%, 验证码位置的坐标默认为缩放与布局100%的坐标，需乘以1.25才能符合本系统的验证码坐标
rangle =(
    int(location['x'])*1.25,
    int(location['y'])*1.25,
    int(location['x'])*1.25+size['width']*1.25,
    int(location['y'])*1.25+size['height']*1.25
)
time.sleep(2)

i = Image.open('./aa.png')
code_img_name = './code.png'
# crop根据区域进行图片裁剪
frame = i.crop(rangle)
frame.save(code_img_name)

# chaojiying = Chaojiying_Client('whxchaojiying', '20210405QED@', '914815')
# im = open('./code.png', 'rb').read()
# result = chaojiying.PostPic(im, 9004)['pic_str'] # 'x,y | x,y'
# result = str(result)
result = '307, 76|147, 189|315, 184'
print(result)

# 将返回值转化为列表 [[x,y],[x,y]]
all_list = []
if '|' in result:
    list_1 = result.split('|')
    count_1 = len(list_1)
    for i in range(count_1):
        xy_list = []
        x = int(list_1[i].split(',')[0])
        y = int(list_1[i].split(',')[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    x = int(result.split(',')[0])
    y = int(result.split(',')[1])
    xy_list = []
    xy_list.append(x)
    xy_list.append(y)
    all_list.append(xy_list)
print(all_list)
# 遍历列表，使用动作链对每一个列表元素对应的x,y指定的位置进行点击操作
for l in all_list:
    x = l[0]
    print(x)
    y = l[1]
    print(y)
    # 得到的坐标为系统显示缩放125%中浏览器的坐标，move_to_element_with_offset是在原来系统显示缩放100%进行移动的，所以乘以0.8是125%的坐标改为100%的坐标
    ActionChains(bro).move_to_element_with_offset(code_img_ele, x*0.8, y*0.8).click().perform()
    time.sleep(1)

